package com.shisfish.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shisfish
 * @date 2020/1/17
 */
@Aspect
@Component
public class HttpAspect {

    private static Logger LOGGER = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.shisfish.controller.TestController.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        LOGGER.info("before");

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        LOGGER.info("url={}", request.getRequestURL());
        LOGGER.info("method={}", request.getMethod());
        LOGGER.info("ip={}", request.getRemoteAddr());

        LOGGER.info("classMethod={}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        LOGGER.info("classArgs={}", joinPoint.getArgs());

    }

    /**
     * 如果定义了@Around，return的对象，即为整个请求返回的对象。
     * 所以不能不定义为void，不然会返回null。
     * 也不能修改return的值，如果统一修改呢？
     *
     * @param joinPoint
     * @return
     */
    @Around(value = "log()")
    public Object around(ProceedingJoinPoint joinPoint) {
        LOGGER.info("around");
        Object obj = null;
        try {
            obj = joinPoint.proceed();
            LOGGER.info("proceed={}", obj);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }

    @After("log()")
    public void doAfter(JoinPoint joinPoint) {
        LOGGER.info("after");
        LOGGER.info("classMethod={}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        LOGGER.info("classArgs={}", joinPoint.getArgs());
    }

    @AfterReturning(value = "log()", returning = "object")
    public void doAfterReturning(JoinPoint joinPoint, Object object) {
        LOGGER.info("afterReturning");
        LOGGER.info("classMethod={}.{} \n classArgs={} \n returning={}",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                joinPoint.getArgs(),
                object == null ? null : object.toString());
    }

}
